package com.controller;

import com.entity.VehicleRefuelRecord;
import com.service.VehicleRefuelRecordService;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/vehicle/refuel")
public class VehicleRefuelRecordController {

    @Autowired
    private VehicleRefuelRecordService vehicleRefuelRecordService;

    @PostMapping
    public VehicleRefuelRecord create(@RequestBody VehicleRefuelRecord vehicleRefuelRecord) {
        return vehicleRefuelRecordService.save(vehicleRefuelRecord);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable(value = "id") Integer id) {
        vehicleRefuelRecordService.deleteById(id);
    }

    @PutMapping("/{id}")
    public VehicleRefuelRecord update(@PathVariable(value = "id") Integer id, @RequestBody VehicleRefuelRecord vehicleRefuelRecord) {
        vehicleRefuelRecord.setId(id);
        return vehicleRefuelRecordService.save(vehicleRefuelRecord);
    }

    @GetMapping("/{id}")
    public VehicleRefuelRecord detail(@PathVariable(value = "id") Integer id) {
        return vehicleRefuelRecordService.findById(id).orElse(null);
    }

    @GetMapping("/page")
    public Page<VehicleRefuelRecord> page(@RequestParam(defaultValue = "1") int pageNum,
                                                  @RequestParam(defaultValue = "10") int pageSize,
                                                  @RequestParam(required = false) String plateNumber) {
        Page<VehicleRefuelRecord> page;
        if (plateNumber != null && !plateNumber.isEmpty()) {
            page = vehicleRefuelRecordService.findByPlateNumberContaining(plateNumber, pageNum, pageSize);
        } else {
            page = vehicleRefuelRecordService.findAll(pageNum, pageSize);
        }
        return page;
    }
}